package com.ruoyi.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.web.config.ServerConfig;
import com.ruoyi.system.commons.utils.JsonValidationUtils;
import com.ruoyi.system.domain.ShotModel;
import com.ruoyi.system.domain.ToolKit;
import com.ruoyi.system.domain.dto.DeleteDto;
import com.ruoyi.system.domain.dto.QueryToolkitDto;
import com.ruoyi.system.service.ShotService;
import com.ruoyi.system.service.ToolKitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 外部资源工具集shot的Controller
 * 
 * @author metaee
 * @date 2023-12-14
 */
@Slf4j
@RestController
@RequestMapping("/toolkit")
public class SysToolkitController extends BaseController
{
    @Autowired
    private ToolKitService toolKitService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ShotService shotService;


    @PostMapping("/update")
    public R update(@RequestBody ToolKit toolKit){
        if (toolKit.getId() == null){
            return R.fail("必须提供要修改的toolkit的id");
        }
        System.out.println(toolKit);

        toolKit.setGmtModified(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        boolean res = toolKitService.updateById(toolKit);
        if (res){
            return R.ok(null,"修改成功！");
        }else {
            return R.fail("修改失败！");
        }
    }

    @PostMapping("/update-prompt")
    public R updatePrompt(@RequestBody ToolKit toolKit){
        if (toolKit.getId() == null){
            return R.fail("必须提供要修改的toolkit的id");
        }

        toolKit.setGmtModified(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        boolean res = toolKitService.updateById(toolKit);
        if (res){
            return R.ok(null,"修改成功！");
        }else {
            return R.fail("修改失败！");
        }
    }

    @PostMapping("/searchById")
    public R searchPrompt(@RequestBody ToolKit toolKit){
        if (toolKit.getId() == null){
            return R.fail("必须提供要修改的toolkit的id");
        }

        ToolKit resTool = toolKitService.getById(toolKit.getId());
        if (resTool != null){
            return R.ok(resTool,"查询成功！");
        }else {
            return R.fail("查询失败！");
        }
    }


    @PostMapping("/delete")
    public R delete(@RequestBody DeleteDto deleteDto){
        if (deleteDto == null){
            return R.fail("必须提供要删除的toolkit的id");
        }

        boolean res = toolKitService.removeById(deleteDto.getId());

        if (res){
            return R.ok(null,"删除成功！");
        }else {
            return R.fail("删除失败！");
        }
    }

    @PostMapping("/logic-delete")
    public R logicDelete(@RequestBody DeleteDto deleteDto){
        if (deleteDto.getId() == null){
            return R.fail("必须提供要删除的toolkit的id");
        }

        LambdaUpdateWrapper<ToolKit> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ToolKit::getIsDeleted,1).eq(ToolKit::getId,deleteDto.getId());
        boolean res = toolKitService.update(updateWrapper);

        if (res){
            return R.ok(null,"删除成功！");
        }else {
            return R.fail("删除失败！");
        }
    }

    @PostMapping("/list")
    public R list(@RequestBody QueryToolkitDto queryToolkitDto){
        if (queryToolkitDto.getPage() == null || queryToolkitDto.getPage() == 0){
            queryToolkitDto.setPage(1L);
        }
        if (queryToolkitDto.getSize() == null || queryToolkitDto.getSize() == 0){
            queryToolkitDto.setSize(10L);
        }
        Page<ToolKit> page = new Page<>(queryToolkitDto.getPage(), queryToolkitDto.getSize());
        LambdaQueryWrapper<ToolKit> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.select("t_tool_kit.*", "sys_user.user_name").
//        queryWrapper.
//        queryWrapper.eq("is_deleted", 0);
        queryWrapper.like(ToolKit::getTkName, queryToolkitDto.getName());
//        queryWrapper.l
        queryWrapper.eq(ToolKit::getIsDeleted,0);
        //queryWrapper.like(ToolKit::getTkName,queryToolkitDto.getName());


        Page<ToolKit> pageResult = toolKitService.selectTookit(page, queryWrapper);
        System.out.println(pageResult);
        return R.ok(pageResult);
    }
    @PostMapping("/add")
    public R add(@RequestBody ToolKit toolKit){
        toolKit.setCreator(SecurityUtils.getUserId());
        toolKit.setGmtCreated(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        boolean res = toolKitService.save(toolKit);
        if (res){
            return R.ok(null,"新增成功！");
        }else {
            return R.fail("保存失败！");
        }
    }

    @PostMapping(value = "/registry", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R addToolKitByJsonFile(@RequestParam("file") MultipartFile file) throws IOException {
        /**@Description: 解析json文件，并且注册进表里，
         * @param [file]
         * @return R
         */
        if (file == null) {
            return R.fail("请上传文件！");
        }

        String fileOriginalName = file.getOriginalFilename();
        log.info("file original name:"+fileOriginalName);
        if (!fileOriginalName.endsWith(".json")) {
            return R.fail("上传失败！请上传json文件！");
        }


        String fileName = FileUploadUtils.extractFilename(file);
        log.info("new file name:",fileName);

        //将文件传输到absPath 当前服务器路径下 /profile文件夹下 ，这个要确定一下路径到底是怎么个路径
        String url = serverConfig.getUrl() + Constants.RESOURCE_PREFIX + "/" + fileName;
        String absPath = FileUploadUtils.getAbsoluteFile(RuoYiConfig.getProfile(), fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));//存储文件

        //注册到数据库
        ToolKit toolKit = new ToolKit();
        toolKit.setCreator(SecurityUtils.getUserId());
        toolKit.setGmtCreated(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        toolKit.setGmtModified(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        toolKit.setIsDeleted(0);

        //注册
        String jsonStr = new String(Files.readAllBytes(Paths.get(absPath)));
        boolean isValid = JsonValidationUtils.schemaValidation(JsonValidationUtils.TOOLKIT_JSON_SCHEMA,jsonStr);
        if (!isValid) {
            return R.fail("注册失败！json格式校验失败！请检查提交的json串");
        }
        JSONObject jsonObject = JSON.parseObject(jsonStr);

        // 模型基本信息
        String toolKitName = jsonObject.getString("tool_kit_name");
        if(toolKitName.equals("")){
            return R.fail("注册失败！必须提供工具集名称！");
        }else {
            LambdaQueryWrapper<ToolKit> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ToolKit::getTkName,toolKitName).eq(ToolKit::getIsDeleted,0);
            List<ToolKit> tkDetector = toolKitService.list(queryWrapper);
            if (tkDetector.size() > 0) {
                return R.fail("该工具集已存在！请修改后再试！");
            }
        }
        String toolKitRole = jsonObject.getString("tool_kit_role");
        String description = jsonObject.getString("description");
        String intention = jsonObject.getString("intention");
        String promptTemplate = jsonObject.containsKey("prompt_template") ? jsonObject.getString("prompt_template") : "";
        JSONArray shotsArray = jsonObject.containsKey("shots") ? jsonObject.getJSONArray("shots") : null;
        toolKit.setTkName(toolKitName);
        toolKit.setTkRole(toolKitRole);
        toolKit.setTkDesc(description);
        toolKit.setTkIntention(intention);
        //prompt template todo:这个到底是用户提供还是我们要拼接的，如果需要用户提供，请忽视并删除todo,如果不是，请填写这里的代码
        toolKit.setTkPrompt(promptTemplate);
        toolKit.setJsonFileUrl(url);

        //落库前检查有没有重名的
        LambdaQueryWrapper<ToolKit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ToolKit::getTkName,toolKitName);
        queryWrapper.eq(ToolKit::getIsDeleted,0);
        long ret = toolKitService.count(queryWrapper);
        if (ret > 0) {
            return R.fail("该工具集合已存在！");
        }
        toolKitService.save(toolKit);

        //shots 落库
        if (shotsArray != null) {
            for (int j = 0; j < shotsArray.size(); j++) {
                JSONObject shotItemJson = shotsArray.getJSONObject(j);

                String queryInput = shotItemJson.getString("query_input");
                String expectedOutput = shotItemJson.getString("expected_output");

                ShotModel shotModel = new ShotModel();
                shotModel.setStToolsName(toolKitName);
                shotModel.setStQueryInput(queryInput);
                shotModel.setStExpectedOutput(expectedOutput);
                shotModel.setGmtCreated(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                shotModel.setGmtModified(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                shotModel.setCreator(SecurityUtils.getUserId());
                shotModel.setIsDeleted(0);
                shotModel.setIsToolkit(1);

                shotService.save(shotModel);
            }
        }
        return R.ok("上传成功");
    }


}
